package com.oweight.sagacious.auth.client.jwt;

import com.alibaba.fastjson.JSONObject;
import com.oweight.sagacious.api.model.user.PersonInfo;
import com.oweight.sagacious.auth.client.config.UserAuthConfig;
import com.oweight.sagacious.auth.common.util.jwt.IJWTInfo;
import com.oweight.sagacious.auth.common.util.jwt.JWTHelper;
import com.oweight.sagacious.common.exception.auth.UserTokenException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 用户授权
 *
 * @author SAGE
 * @version v1 2019/10/19 15:06
 */
@Configuration
public class UserAuthUtil {

    @Autowired
    private UserAuthConfig userAuthConfig;

    public IJWTInfo getInfoFromToken(String token) throws Exception {
        try {

            if (token.contains("{")) {
                Map<String, String> parse = (Map) JSONObject.parse(token);
                token = parse.get("data");
            }
            IJWTInfo infoFromToken = JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());
            return infoFromToken;
        } catch (ExpiredJwtException ex) {
            throw new UserTokenException("用户Token失效！");
        } catch (SignatureException ex) {
            throw new UserTokenException("用户Token签名错误！");
        } catch (IllegalArgumentException ex) {
            throw new UserTokenException("用户Token为空！");
        }
    }

    public PersonInfo getInfoFromToken2(String token) throws Exception {
        try {

            if (token.contains("{")) {
                Map<String, String> parse = (Map) JSONObject.parse(token);
                token = parse.get("data");
            }
            PersonInfo personInfo = JWTHelper.getInfoFromToken2(token, userAuthConfig.getPubKeyByte());
            return personInfo;
        } catch (ExpiredJwtException ex) {
            throw new UserTokenException("用户Token失效！");
        } catch (SignatureException ex) {
            throw new UserTokenException("用户Token签名错误！");
        } catch (IllegalArgumentException ex) {
            throw new UserTokenException("用户Token为空！");
        }
    }
}
